package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Item;
import com.itheima.service.ItemService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 题库Controller
 */
@RestController
@RequestMapping("/item")
public class ItemController {

    @Reference
    private ItemService itemService;

    //题库分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = itemService.pageQuery(queryPageBean);
        return pageResult;
    }

    //新增题目
    @RequestMapping("/add")
    public Result add(@RequestBody Item item){
        try {
            itemService.add(item);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.ADD_ITEM_FAIL);
        }
       return new Result(true, MessageConstant.ADD_ITEM_SUCCESS);

    }

    //删除题目
    @PreAuthorize("hasAuthority('ITEM_DELETE')")//配置权限
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            itemService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
           return new Result(false, MessageConstant.DELETE_ITEM_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_ITEM_SUCCESS);

    }

    //查询回显检查项
    @RequestMapping("/edit")
    public Result edit(@RequestBody Item item){
        try {
            itemService.edit(item);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
           return new Result(false, MessageConstant.EDIT_ITEM_FAIL);
        }
       return new Result(true, MessageConstant.EDIT_ITEM_SUCCESS);

    }

    //根据id查找题目
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Item item = itemService.findById(id);
           return new Result(true, MessageConstant.QUERY_ITEM_SUCCESS, item);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
           return new Result(false, MessageConstant.QUERY_ITEM_FAIL);
        }

    }

    //查询所有题目
    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<Item> list = itemService.findAll();
            return new Result(true, MessageConstant.QUERY_ITEM_SUCCESS, list);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
           return new Result(false, MessageConstant.QUERY_ITEM_FAIL);
        }

    }
}
